package com.kws.tool.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kws.common.core.utils.StringUtils;
import com.kws.system.api.domain.*;
import com.kws.system.api.domain.ResultDto;
import com.kws.tool.dto.*;
import com.kws.tool.exception.EsignDemoException;
import com.kws.tool.service.ContractService;
import com.kws.tool.util.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author :yxy
 * @date : 2024/11/26
 */
@Service
public class ContractServiceImpl implements ContractService {
    private static String eSignHost = EsignDemoConfig.EsignHost;
    private static String eSignAppId = EsignDemoConfig.EsignAppId;
    private static String eSignAppSecret = EsignDemoConfig.EsignAppSecret;
    private static String eSignNotifyUrl= EsignDemoConfig.eSignNotifyUrl;

    /**
     * 上传文件模板
     *
     * @return
     */
    @Override
    public EQBTemplateVo saveContract(MultipartFile file) {
        String fileMD5 = "";
        EQBTemplateVo eqbTemplateVo = new EQBTemplateVo();
        try {
            fileMD5 = EQBUtil.getFileMD5Bytes128(file);
            EsignHttpResponse getUploadUrl = getUploadUrl(file, fileMD5);
            Gson gson = new Gson();
            JsonObject getUploadUrlJsonObject = gson.fromJson(getUploadUrl.getBody(), JsonObject.class);
            JsonObject data = getUploadUrlJsonObject.getAsJsonObject("data");
            //文件id后续发起签署使用
            String fileId = data.get("fileId").getAsString();
            String fileUploadUrl = data.get("fileUploadUrl").getAsString();

            byte[] bytes = file.getBytes();
            //文件上传
            EsignHttpResponse uploadFileResponse = uploadFile(fileUploadUrl, fileMD5, bytes);
            JsonObject uploadFileResponseJsonObject = gson.fromJson(uploadFileResponse.getBody(), JsonObject.class);
            String errCode = uploadFileResponseJsonObject.get("errCode").getAsString();
            System.out.println("文件上传成功，状态码:" + errCode);

            //文件上传成功后文件会有一个异步处理过程，建议轮询文件状态，正常后发起签署
            //查询文件上传状态
            int i = 0;
            EsignHttpResponse fileStatus = null;
            while (i < 3) {
                //{"code":0,"message":"成功","data":{"fileId":"66b61f0e9daa459495062a2869c593c0","fileName":"接入时发现的问题.docx","fileSize":null,
                // "fileStatus":2,"fileDownloadUrl":"https://esignoss.esign.cn/1111564182/922be55d-a0de-4a02-958a-14208c7c3b4f/%E6%8E%A5%E5%85%A5%E6%97%B6%E5%8F%91%E7%8E%B0%E7%9A%84%E9%97%AE%E9%A2%98.docx?Expires=1733745307&OSSAccessKeyId=LTAI4G23YViiKnxTC28ygQzF&Signature=bNvMjCd%2BDdjGX4BqBRuAK4tbHo4%3D",
                // "fileTotalPageCount":0,"pageWidth":null,"pageHeight":null}}
                fileStatus = getFileStatus(fileId);
                JsonObject fileStatusJsonObject = gson.fromJson(fileStatus.getBody(), JsonObject.class);
                String status = fileStatusJsonObject.getAsJsonObject("data").get("fileStatus").getAsString();
                System.out.println(String.format("查询文件状态执行第%s次", i + 1));
                if ("2".equalsIgnoreCase(status) || "5".equalsIgnoreCase(status)) {//查询状态为2或者5代表文件准备完成
                    System.out.println("文件准备完成");
                    break;
                }
                System.out.println("文件未准备完成,等待两秒重新查询");
                TimeUnit.SECONDS.sleep(2);
                i++;
            }
            EQBDto eqbDto = gson.fromJson(fileStatus.getBody(), EQBDto.class);
            EQBFileDto eqbFileDto = eqbDto.getData();
            if (eqbDto.getCode() != 0 && !("2".equalsIgnoreCase(eqbFileDto.getFileStatus()) || "5".equalsIgnoreCase(eqbFileDto.getFileStatus()))) {
                throw new RuntimeException("文件上传失败");
            }
            /* 获取制作合同模板页面*/
            EsignHttpResponse getTemplateCreateUrl = getTemplateCreateUrl(eqbFileDto.getFileName(), eqbFileDto.getFileId());
            JsonObject getTemplateCreateUrlObject = gson.fromJson(getTemplateCreateUrl.getBody(), JsonObject.class);
            String docTemplateCreateUrl = getTemplateCreateUrlObject.getAsJsonObject("data").get("docTemplateCreateUrl").getAsString();//合同编辑页面
            String docTemplateId = getTemplateCreateUrlObject.getAsJsonObject("data").get("docTemplateId").getAsString();//模板id
            String fileDownloadUrl = eqbFileDto.getFileDownloadUrl();

            eqbTemplateVo.setDocTemplateId(docTemplateId);
            eqbTemplateVo.setDocTemplateCreateUrl(docTemplateCreateUrl);
            eqbTemplateVo.setFileDownloadUrl(fileDownloadUrl);
            eqbTemplateVo.setFileId(fileId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("fileMD5Bytes128===" + fileMD5);
        return eqbTemplateVo;
    }

    /**
     * 删除文件模板
     * @param docTemplateId
     * @return
     */
    @Override
    public Boolean deleteContract(String docTemplateId) {
        Gson gson = new Gson();
        try {
            EsignHttpResponse deleteDocTemplate = deleteDocTemplate(docTemplateId);
            JsonObject deleteDocTemplateObject = gson.fromJson(deleteDocTemplate.getBody(), JsonObject.class);
            String code = deleteDocTemplateObject.get("code").getAsString();
            if ("0".equals(code)){
                return true;
            }
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据模板id查询模板控件
     * @param docTemplateId
     * @return
     */
    @Override
    public ResultDto getComponentsInfo(String docTemplateId) {
        Gson gson = new Gson();
        /* 查询合同模板中控件详情*/
        String apiaddr = "/v3/doc-templates/" + docTemplateId;

        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = null;
        //请求方法
        EsignRequestType requestType = EsignRequestType.GET;
        //生成签名鉴权方式的的header
        Map<String, String> header = null;
        EsignHttpResponse esignHttpResponse = null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
            //发起接口请求
            esignHttpResponse = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);

        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(esignHttpResponse.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 填充模板--合同金额、甲方、乙方
     * @return
     */
    @Override
    public ResultDto createByDocTemplate(CreateTemplate createTemplate) {
        Gson gson = new Gson();
        String apiaddr = "/v3/files/create-by-doc-template";
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成签名鉴权方式的的header
        Map<String, String> header = null;
        EsignHttpResponse esignHttpResponse = null;
        String map = JSONObject.toJSONString(createTemplate);
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret,map , requestType.name(), apiaddr, true);
            //发起接口请求
            esignHttpResponse = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, map, header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(esignHttpResponse.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 创建合同并发起
     * @param createContractPo
     * @return
     */
    @Override
    public ResultDto createContract(CreateContractDto createContractPo) {
        String apiaddr = "/v3/sign-flow/create-by-file";
        Gson gson = new Gson();
        String fileId = createContractPo.getFileId();
        String fileName = createContractPo.getFileName();
        QuerySignContractRq querySignContractRq = new QuerySignContractRq();
        ArrayList<DocsRq> docsRqs = new ArrayList<>();
        DocsRq docsRq = new DocsRq();
        docsRq.setFileId(fileId);
        docsRq.setFileName(fileName);
        docsRqs.add(docsRq);
        SignFlowConfigRq signFlowConfigRq = new SignFlowConfigRq();
        signFlowConfigRq.setSignFlowTitle(createContractPo.getSignFlowTitle());
        signFlowConfigRq.setAutoFinish(true);//自动完结
        signFlowConfigRq.setAutoStart(true);//自动开启签署
        //身份校验配置项（当开发者指定的签署人信息与该签署人在e签宝已有的身份信息不一致时如何处理），默认：true
        // true - 接口报错（提示：传入的指定签署人信息与实名信息不一致相关报错）false - 不报错，正常发起
        signFlowConfigRq.setIdentityVerify(true);
        signFlowConfigRq.setNotifyUrl(eSignNotifyUrl+"/merchant/contract/callBackUrl");
        ArrayList<SignersRq> signersRqs = new ArrayList<>();

        //企业签章
        SignersRq signersRq = new SignersRq();
        signersRq.setSignerType(1);
        NoticeConfigRq noticeConfigRq = new NoticeConfigRq();
        noticeConfigRq.setNoticeTypes(1);
        signersRq.setNoticeConfig(noticeConfigRq);
        OrgSignerInfoRq orgSignerInfoRq = new OrgSignerInfoRq();
        orgSignerInfoRq.setOrgName(createContractPo.getMerchantName());//企业名称
        OrgInfoRq orgInfoRq = new OrgInfoRq();
        orgInfoRq.setLegalRepIDCardNum(createContractPo.getMerchantCode());//企业编码
        orgInfoRq.setLegalRepIDCardType("CRED_ORG_USCC");//企业编码类型


        TransactorInfoRq transactorInfoRq = new TransactorInfoRq();
        transactorInfoRq.setPsnAccount(createContractPo.getMerchantUserPhone());//手机号
        PsnInfoRq psnInfoRq = new PsnInfoRq();
        psnInfoRq.setPsnName(createContractPo.getMerchantUserName());//姓名
        psnInfoRq.setPsnIDCardNum(createContractPo.getMerchantUserIdCard());//证件号
        psnInfoRq.setPsnIDCardType("CRED_PSN_CH_IDCARD");//证件号类型
        transactorInfoRq.setPsnInfo(psnInfoRq);


        orgSignerInfoRq.setOrgInfo(orgInfoRq);
        orgSignerInfoRq.setTransactorInfo(transactorInfoRq);
        signersRq.setOrgSignerInfo(orgSignerInfoRq);

        ArrayList<SignFieldsRq> signFieldsRqs = new ArrayList<>();
        List<FieldPositionPo> merchantFieldPosition = createContractPo.getMerchantFieldPosition();
        merchantFieldPosition.forEach(x->{
            SignFieldsRq signFieldsRq = new SignFieldsRq();
            signFieldsRq.setFileId(fileId);
            NormalSignFieldConfigRq normalSignFieldConfigRq = new NormalSignFieldConfigRq();
            normalSignFieldConfigRq.setAutoSign(false);
            normalSignFieldConfigRq.setFreeMode(false);
            normalSignFieldConfigRq.setSignFieldStyle(1);//1 - 单页签章，2 - 骑缝签章
            normalSignFieldConfigRq.setMovableSignField(false);
            SignFieldPositionRq signFieldPositionRq = new SignFieldPositionRq();
            signFieldPositionRq.setPositionPage(x.getPositionPage());
            signFieldPositionRq.setPositionX(x.getPositionX());
            signFieldPositionRq.setPositionY(x.getPositionY());
            normalSignFieldConfigRq.setSignFieldPosition(signFieldPositionRq);
            signFieldsRq.setNormalSignFieldConfig(normalSignFieldConfigRq);
            signFieldsRqs.add(signFieldsRq);
        });
        signersRq.setSignFields(signFieldsRqs);
        signersRqs.add(signersRq);

        //用户签章
        SignersRq signersRq1 = new SignersRq();
        signersRq1.setSignerType(0);
        NoticeConfigRq noticeConfigRq1 = new NoticeConfigRq();
        noticeConfigRq1.setNoticeTypes(1);
        signersRq1.setNoticeConfig(noticeConfigRq1);
        PsnSignerInfoRq psnSignerInfoRq = new PsnSignerInfoRq();
        psnSignerInfoRq.setPsnAccount(createContractPo.getUserPhone());//用户手机号
        PsnInfoRq psnInfoRq1 = new PsnInfoRq();
        psnInfoRq1.setPsnName(createContractPo.getUserName());//用户名称
        psnSignerInfoRq.setPsnInfo(psnInfoRq1);
        signersRq1.setPsnSignerInfo(psnSignerInfoRq);

        List<FieldPositionPo> userFieldPosition = createContractPo.getUserFieldPosition();
        ArrayList<SignFieldsRq> signFieldsRqs1 = new ArrayList<>();
        userFieldPosition.forEach(x->{
            SignFieldsRq signFieldsRq1 = new SignFieldsRq();
            signFieldsRq1.setFileId(fileId);
            NormalSignFieldConfigRq normalSignFieldConfigRq1 = new NormalSignFieldConfigRq();
            normalSignFieldConfigRq1.setAutoSign(false);
            normalSignFieldConfigRq1.setFreeMode(false);
            normalSignFieldConfigRq1.setSignFieldStyle(1);//1 - 单页签章，2 - 骑缝签章
            normalSignFieldConfigRq1.setMovableSignField(false);
            SignFieldPositionRq signFieldPositionRq1 = new SignFieldPositionRq();
            signFieldPositionRq1.setPositionPage(x.getPositionPage());
            signFieldPositionRq1.setPositionX(x.getPositionX());
            signFieldPositionRq1.setPositionY(x.getPositionY());
            normalSignFieldConfigRq1.setSignFieldPosition(signFieldPositionRq1);
            signFieldsRq1.setNormalSignFieldConfig(normalSignFieldConfigRq1);
            signFieldsRqs1.add(signFieldsRq1);
        });
        signersRq1.setSignFields(signFieldsRqs1);
        signersRqs.add(signersRq1);

        querySignContractRq.setDocs(docsRqs);
        querySignContractRq.setSignFlowConfig(signFlowConfigRq);
        querySignContractRq.setSigners(signersRqs);
        System.out.println(querySignContractRq);
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成请求签名鉴权方式的Header
        Map<String, String> header = null;
        EsignHttpResponse esignHttpResponse = null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, JSON.toJSONString(querySignContractRq), requestType.name(), apiaddr, true);
            esignHttpResponse = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, JSON.toJSONString(querySignContractRq), header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(esignHttpResponse.getBody(), ResultDto.class);
        //发起接口请求
        return resultDto;
    }

    /**
     * 获取签署链接--查看合同--免登录，任何人可查看
     * @return
     */
    @Override
    public ResultDto signViewLink(String signFlowId) {
        Gson gson = new Gson();
        String apiaddr = "/v3/sign-flow/" + signFlowId + "/sign-url";
        String jsonParm="{\n" +
                "  \"clientType\": \"ALL\",\n" +
                "  \"needLogin\": false,\n" +
                "  \"operator\": {\n" +
                "    \"psnAccount\": \"\"\n" +
                "  },\n" +
                "  \"urlType\": 1\n" +
                "}";
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成请求签名鉴权方式的Header
        Map<String, String> header = null;
        EsignHttpResponse signUrl=null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
        //发起接口请求
            signUrl = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType,jsonParm, header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        JsonObject signUrlJsonObject = gson.fromJson(signUrl.getBody(), JsonObject.class);
        JsonObject signUrlData = signUrlJsonObject.getAsJsonObject("data");
        ResultDto resultDto = gson.fromJson(signUrl.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 获取签署链接
     * @param querySignUrlRq
     * @return
     */
    @Override
    public ResultDto signLink(QuerySignUrlRq querySignUrlRq) {
        String signFlowId = querySignUrlRq.getSignFlowId();
        if (StringUtils.isEmpty(signFlowId)){
            throw new RuntimeException("签署流程id不能为空");
        }
        Gson gson = new Gson();
        String apiaddr = "/v3/sign-flow/" + signFlowId + "/sign-url";
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成请求签名鉴权方式的Header
        Map<String, String> header = null;
        EsignHttpResponse signUrl=null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret,JSON.toJSONString(querySignUrlRq) , requestType.name(), apiaddr, true);
            //发起接口请求
            signUrl = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType,JSON.toJSONString(querySignUrlRq), header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        JsonObject signUrlJsonObject = gson.fromJson(signUrl.getBody(), JsonObject.class);
        JsonObject signUrlData = signUrlJsonObject.getAsJsonObject("data");
        ResultDto resultDto = gson.fromJson(signUrl.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 文件下载地址
     * @param signFlowId
     * @return
     */
    @Override
    public ResultDto fileDownloadUrl(String signFlowId) {
        Gson gson = new Gson();
        String apiaddr = "/v3/sign-flow/" + signFlowId + "/file-download-url";
        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = null;
        //请求方法
        EsignRequestType requestType = EsignRequestType.GET;
        //生成签名鉴权方式的的header
        Map<String, String> header = null;
        EsignHttpResponse fileDownloadUrl = null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
            //发起接口请求
            fileDownloadUrl = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(fileDownloadUrl.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 查询签署流程列表
     * @return
     */
    @Override
    public ResultDto signFlowList(SignFlowRq signFlowRq) {
        Gson gson = new Gson();
        String apiaddr = "/v3/sign-flow/sign-flow-list";

        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //发起接口请求
        EsignHttpResponse signFlowList = null;
        try {
            //生成签名鉴权方式的的header
            Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, JSON.toJSONString(signFlowRq), requestType.name(), apiaddr, true);
            signFlowList = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, JSON.toJSONString(signFlowRq), header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(signFlowList.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 查询签署流程详情
     * @param signFlowId
     * @return
     */
    @Override
    public ResultDto signFlowDetail(String signFlowId) {
        Gson gson = new Gson();
        String apiaddr = "/v3/sign-flow/" + signFlowId + "/detail";
        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = null;
        //请求方法
        EsignRequestType requestType = EsignRequestType.GET;
        //生成签名鉴权方式的的header
        Map<String, String> header = null;
        EsignHttpResponse signFlowDetail = null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
            //发起接口请求
            signFlowDetail = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(signFlowDetail.getBody(), ResultDto.class);
        return resultDto;
    }

    /**
     * 撤销签署流程
     * @param signFlowRevoke
     * @return
     */
    @Override
    public ResultDto signFlowRevoke(SignFlowRevoke signFlowRevoke) {
        Gson gson = new Gson();
        String signFlowId = signFlowRevoke.getSignFlowId();
        String revokeReason = signFlowRevoke.getRevokeReason();
        String apiaddr = "/v3/sign-flow/" + signFlowId + "/revoke";
        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = "{\n" +
                "    \"revokeReason\": \"" + revokeReason + "\"\n" +
                "}";
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成签名鉴权方式的的header
        Map<String, String> header = null;
        EsignHttpResponse response = null;
        try {
            header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
            //发起接口请求
            response = EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
        } catch (EsignDemoException e) {
            e.printStackTrace();
        }
        ResultDto resultDto = gson.fromJson(response.getBody(), ResultDto.class);
        return resultDto;
    }


    /**
     * 删除模板
     */
    private static EsignHttpResponse deleteDocTemplate(String docTemplateId) throws EsignDemoException {
        String apiaddr="/v3/doc-templates/"+docTemplateId;

        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm="{}";
        //请求方法
        EsignRequestType requestType= EsignRequestType.DELETE;
        //生成签名鉴权方式的的header
        Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId,eSignAppSecret,jsonParm,requestType.name(),apiaddr,true);
        //发起接口请求
        return EsignHttpHelper.doCommHttp(eSignHost, apiaddr,requestType , jsonParm, header,true);
    }

    /**
     * 获取文件上传地址
     *
     * @return
     */
    public static EsignHttpResponse getUploadUrl(MultipartFile file, String fileMD5) throws EsignDemoException {
        //自定义的文件封装类，传入文件地址可以获取文件的名称大小,文件流等数据
        String apiaddr = "/v3/files/file-upload-url";
        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String originalFilename = file.getOriginalFilename();
        boolean flag = false;
        if (!originalFilename.endsWith("pdf")) {
            flag = true;
        }
        String jsonParm = "{\n" +
                "    \"contentMd5\": \"" + fileMD5 + "\",\n" +
                "    \"fileName\":\"" + originalFilename + "\"," +
                "    \"fileSize\": " + file.getSize() + ",\n" +
                "    \"convertToPDF\": " + flag + ",\n" +
                "    \"contentType\": \"" + EsignHeaderConstant.CONTENTTYPE_STREAM.VALUE() + "\"\n" +
                "}";
        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成签名鉴权方式的的header
        Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
        //发起接口请求
        return EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
    }

    /**
     * 文件流上传
     *
     * @return
     */
    public static EsignHttpResponse uploadFile(String uploadUrl, String fileMD5, byte[] bytes) throws EsignDemoException {
        //请求方法
        EsignRequestType requestType = EsignRequestType.PUT;
        return EsignHttpHelper.doUploadHttp(uploadUrl, requestType, bytes, fileMD5, EsignHeaderConstant.CONTENTTYPE_STREAM.VALUE(), true);
    }

    /**
     * 获取文件上传状态
     */
    public static EsignHttpResponse getFileStatus(String fileId) throws EsignDemoException {
        String apiaddr = "/v3/files/" + fileId;

        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = null;
        //请求方法
        EsignRequestType requestType = EsignRequestType.GET;
        //生成签名鉴权方式的的header
        Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
        //发起接口请求
        return EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
    }

    /**
     * 获取制作合同模板页面
     *
     * @return
     * @throws EsignDemoException
     */
    private static EsignHttpResponse getTemplateCreateUrl(String fileName, String fileId) throws EsignDemoException {
        String apiaddr = "/v3/doc-templates/doc-template-create-url";
        //请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
        String jsonParm = "{\"docTemplateName\":\"" + fileName + "\",\"docTemplateType\":0,\"fileId\":\"" + fileId + "\",\"redirectUrl\":\"https://www.esign.cn\"}";

        //请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        //生成签名鉴权方式的的header
        Map<String, String> header = EsignHttpHelper.signAndBuildSignAndJsonHeader(eSignAppId, eSignAppSecret, jsonParm, requestType.name(), apiaddr, true);
        //发起接口请求
        return EsignHttpHelper.doCommHttp(eSignHost, apiaddr, requestType, jsonParm, header, true);
    }


}
